package set;

import java.util.Comparator;
import java.util.TreeSet;

//自然排序Comparable的使用
//compareTo 方法被称为Comparable的自然比较方法。
public class Comparable使用 {
    public static void main(String[] args) {
        //匿名内部类
        TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                int i1 = s2.getAge() - s1.getAge();
                int i2 = i1 == 0 ? s2.getName().compareTo(s1.getName()) : i1;
                return i2;
            }
        });

        Student s1 = new Student("wa朝", 25);
        Student s2 = new Student("ma汉", 26);
        Student s3 = new Student("zh龙", 23);
        Student s5 = new Student("zh虎", 22);
        Student s4 = new Student("aa虎", 22);

        //添加失败,保证唯一性
        Student s6 = new Student("zh虎", 22);


        //添加学生
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);
        ts.add(s6);
        //遍历集合
        for (Student t : ts) {
            System.out.println(t);
        }
    }
}
